import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:study_demo/base/BaseController.dart';

final GlobalKey repaintKey = GlobalKey(debugLabel: 'color');

class PickColorController extends BaseController {
  Future<ui.Color?> getPixelColor(BuildContext context, Offset point) async {
    final RenderRepaintBoundary boundary =
        repaintKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    final ui.Image image =
        await boundary.toImage(pixelRatio: ui.window.devicePixelRatio);
    final byteData = await image.toByteData();
    if (byteData != null) {
      final int colorCode = byteData.getUint32(
          (point.dx * image.width + point.dy).toInt(), Endian.host);
      return Color(colorCode);
    }
    return null;
  }
}
